{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\nmicroTVM with TFLite Models\n===========================\n**Author**: `Tom Gall <https://github.com/tom-gall>`_\n\nThis tutorial is an introduction to working with microTVM and a TFLite\nmodel with Relay.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>If you want to run this tutorial on the microTVM Reference VM, download the Jupyter\n    notebook using the link at the bottom of this page and save it into the TVM directory. Then:\n\n    #. Login to the reference VM with a modified ``vagrant ssh`` command:\n\n        ``$ vagrant ssh -- -L8888:localhost:8888``\n\n    #. Install jupyter:  ``pip install jupyterlab``\n    #. ``cd`` to the TVM directory.\n    #. Install tflite: poetry install -E importer-tflite\n    #. Launch Jupyter Notebook: ``jupyter notebook``\n    #. Copy the localhost URL displayed, and paste it into your browser.\n    #. Navigate to saved Jupyter Notebook (``.ipynb`` file).</p></div>\n\n\nSetup\n-----\n\nInstall TFLite\n^^^^^^^^^^^^^^\n\nTo get started, TFLite package needs to be installed as prerequisite. You can do this in two ways:\n\n1. Install tflite with ``pip``\n\n    .. code-block:: bash\n\n      pip install tflite=2.1.0 --user\n\n2. Generate the TFLite package yourself. The steps are the following:\n\n    Get the flatc compiler.\n    Please refer to https://github.com/google/flatbuffers for details\n    and make sure it is properly installed.\n\n    .. code-block:: bash\n\n      flatc --version\n\n    Get the TFLite schema.\n\n    .. code-block:: bash\n\n      wget https://raw.githubusercontent.com/tensorflow/tensorflow/r1.13/tensorflow/lite/schema/schema.fbs\n\n    Generate TFLite package.\n\n    .. code-block:: bash\n\n      flatc --python schema.fbs\n\n    Add the current folder (which contains generated tflite module) to PYTHONPATH.\n\n    .. code-block:: bash\n\n      export PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}$(pwd)\n\nTo validate that the TFLite package was installed successfully, ``python -c \"import tflite\"``\n\nInstall Zephyr (physical hardware only)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWhen running this tutorial with a host simulation (the default), you can use the host ``gcc`` to\nbuild a firmware image that simulates the device. When compiling to run on physical hardware, you\nneed to install a *toolchain* plus some target-specific dependencies. microTVM allows you to\nsupply any compiler and runtime that can launch the TVM RPC server, but to get started, this\ntutorial relies on the Zephyr RTOS to provide these pieces.\n\nYou can install Zephyr by following the\n`Installation Instructions <https://docs.zephyrproject.org/latest/getting_started/index.html>`_.\n\nAside: Recreating your own Pre-Trained TFLite model\n The tutorial downloads a pretrained TFLite model. When working with microcontrollers\n you need to be mindful these are highly resource constrained devices as such standard\n models like MobileNet may not fit into their modest memory.\n\n For this tutorial, we'll make use of one of the TF Micro example models.\n\n If you wish to replicate the training steps see:\n https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/micro/examples/hello_world/train\n\n   .. note::\n\n     If you accidentally download the example pretrained model from:\n\n     ``wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/micro/hello_world_2020_04_13.zip``\n\n     this will fail due to an unimplemented opcode (114)\n\nLoad and prepare the Pre-Trained Model\n--------------------------------------\n\nLoad the pretrained TFLite model from a file in your current\ndirectory into a buffer\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nimport numpy as np\nimport logging\n\nimport tvm\nimport tvm.micro as micro\nfrom tvm.contrib.download import download_testdata\nfrom tvm.contrib import graph_executor, utils\nfrom tvm import relay\n\nmodel_url = \"https://people.linaro.org/~tom.gall/sine_model.tflite\"\nmodel_file = \"sine_model.tflite\"\nmodel_path = download_testdata(model_url, model_file, module=\"data\")\n\ntflite_model_buf = open(model_path, \"rb\").read()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Using the buffer, transform into a tflite model python object\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "try:\n    import tflite\n\n    tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n    import tflite.Model\n\n    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Print out the version of the model\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "version = tflite_model.Version()\nprint(\"Model Version: \" + str(version))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Parse the python model object to convert it into a relay module\nand weights.\nIt is important to note that the input tensor name must match what\nis contained in the model.\n\nIf you are unsure what that might be, this can be discovered by using\nthe ``visualize.py`` script within the Tensorflow project.\nSee `How do I inspect a .tflite file? <https://www.tensorflow.org/lite/guide/faq>`_\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "input_tensor = \"dense_4_input\"\ninput_shape = (1,)\ninput_dtype = \"float32\"\n\nmod, params = relay.frontend.from_tflite(\n    tflite_model, shape_dict={input_tensor: input_shape}, dtype_dict={input_tensor: input_dtype}\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Defining the target\n-------------------\n\nNow we create a build config for relay, turning off two options and then calling relay.build which\nwill result in a C source file for the selected TARGET. When running on a simulated target of the\nsame architecture as the host (where this Python script is executed) choose \"host\" below for the\nTARGET and a proper board/VM to run it (Zephyr will create the right QEMU VM based on BOARD. In\nthe example below the x86 arch is selected and a x86 VM is picked up accordingly:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "TARGET = tvm.target.target.micro(\"host\")\nBOARD = \"qemu_x86\"\n#\n# Compiling for physical hardware\n#  When running on physical hardware, choose a TARGET and a BOARD that describe the hardware. The\n#  STM32F746 Nucleo target and board is chosen in the example below. Another option would be to\n#  choose the STM32F746 Discovery board instead. Since that board has the same MCU as the Nucleo\n#  board but a couple of wirings and configs differ, it's necessary to select the \"stm32f746g_disco\"\n#  board to generated the right firmware image.\n#\n#  TARGET = tvm.target.target.micro(\"stm32f746xx\")\n#  BOARD = \"nucleo_f746zg\" # or \"stm32f746g_disco#\"\n#\n#  For some boards, Zephyr runs them emulated by default, using QEMU. For example, below is the\n#  TARGET and BOARD used to build a microTVM firmware for the mps2-an521 board. Since that board\n#  runs emulated by default on Zephyr the suffix \"-qemu\" is added to the board name to inform\n#  microTVM that the QEMU transporter must be used to communicate with the board. If the board name\n#  already has the prefix \"qemu_\", like \"qemu_x86\", then it's not necessary to add that suffix.\n#\n#  TARGET = tvm.target.target.micro(\"mps2_an521\")\n#  BOARD = \"mps2_an521-qemu\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now, compile the model for the target:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "with tvm.transform.PassContext(\n    opt_level=3, config={\"tir.disable_vectorize\": True}, disabled_pass=[\"AlterOpLayout\"]\n):\n    module = relay.build(mod, target=TARGET, params=params)\n\n\n# Inspecting the compilation output\n# ---------------------------------\n#\n# The compilation process has produced some C code implementing the operators in this graph. We\n# can inspect it by printing the CSourceModule contents (for the purposes of this tutorial, let's\n# just print the first 10 lines):\n\nc_source_module = module.get_lib().imported_modules[0]\nassert c_source_module.type_key == \"c\", \"tutorial is broken\"\n\nc_source_code = c_source_module.get_source()\nfirst_few_lines = c_source_code.split(\"\\n\")[:10]\nassert any(\n    l.startswith(\"TVM_DLL int32_t tvmgen_default_\") for l in first_few_lines\n), f\"tutorial is broken: {first_few_lines!r}\"\nprint(\"\\n\".join(first_few_lines))\n\n\n# Compiling the generated code\n# ----------------------------\n#\n# Now we need to incorporate the generated C code into a project that allows us to run inference on the\n# device. The simplest way to do this is to integrate it yourself, using microTVM's standard output format\n# (:doc:`Model Library Format` </dev/model_library_format>`). This is a tarball with a standard layout:\n\n# Get a temporary path where we can store the tarball (since this is running as a tutorial).\nimport tempfile\n\nfd, model_library_format_tar_path = tempfile.mkstemp()\nos.close(fd)\nos.unlink(model_library_format_tar_path)\ntvm.micro.export_model_library_format(module, model_library_format_tar_path)\n\nimport tarfile\n\nwith tarfile.open(model_library_format_tar_path, \"r:*\") as tar_f:\n    print(\"\\n\".join(f\" - {m.name}\" for m in tar_f.getmembers()))\n\n# Cleanup for tutorial:\nos.unlink(model_library_format_tar_path)\n\n\n# TVM also provides a standard way for embedded platforms to automatically generate a standalone\n# project, compile and flash it to a target, and communicate with it using the standard TVM RPC\n# protocol. The Model Library Format serves as the model input to this process. When embedded\n# platforms provide such an integration, they can be used directly by TVM for both host-driven\n# inference and autotuning . This integration is provided by the\n# `microTVM Project API` <https://github.com/apache/tvm-rfcs/blob/main/rfcs/0008-microtvm-project-api.md>_,\n#\n# Embedded platforms need to provide a Template Project containing a microTVM API Server (typically,\n# this lives in a file ``microtvm_api_server.py`` in the root directory). Let's use the example ``host``\n# project in this tutorial, which simulates the device using a POSIX subprocess and pipes:\n\nimport subprocess\nimport pathlib\n\nrepo_root = pathlib.Path(\n    subprocess.check_output([\"git\", \"rev-parse\", \"--show-toplevel\"], encoding=\"utf-8\").strip()\n)\ntemplate_project_path = repo_root / \"src\" / \"runtime\" / \"crt\" / \"host\"\nproject_options = {}  # You can use options to provide platform-specific options through TVM.\n\n# Compiling for physical hardware (or an emulated board, like the mps_an521)\n# --------------------------------------------------------------------------\n#  For physical hardware, you can try out the Zephyr platform by using a different template project\n#  and options:\n#\n#     template_project_path = repo_root / \"apps\" / \"microtvm\" / \"zephyr\" / \"template_project\"\n#     project_options = {\"project_type\": \"host_driven\", zephyr_board\": \"nucleo_f746zg\"}}\n\n# Create a temporary directory\nimport tvm.contrib.utils\n\ntemp_dir = tvm.contrib.utils.tempdir()\ngenerated_project_dir = temp_dir / \"generated-project\"\ngenerated_project = tvm.micro.generate_project(\n    template_project_path, module, generated_project_dir, project_options\n)\n\n# Build and flash the project\ngenerated_project.build()\ngenerated_project.flash()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Next, establish a session with the simulated device and run the\ncomputation. The `with session` line would typically flash an attached\nmicrocontroller, but in this tutorial, it simply launches a subprocess\nto stand in for an attached microcontroller.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "with tvm.micro.Session(transport_context_manager=generated_project.transport()) as session:\n    graph_mod = tvm.micro.create_local_graph_executor(\n        module.get_graph_json(), session.get_system_lib(), session.device\n    )\n\n    # Set the model parameters using the lowered parameters produced by `relay.build`.\n    graph_mod.set_input(**module.get_params())\n\n    # The model consumes a single float32 value and returns a predicted sine value.  To pass the\n    # input value we construct a tvm.nd.array object with a single contrived number as input. For\n    # this model values of 0 to 2Pi are acceptable.\n    graph_mod.set_input(input_tensor, tvm.nd.array(np.array([0.5], dtype=\"float32\")))\n    graph_mod.run()\n\n    tvm_output = graph_mod.get_output(0).numpy()\n    print(\"result is: \" + str(tvm_output))"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}